<?php

namespace app\videos\model;

use think\Model;
use think\Db;

class Videos extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'mac_vod';

    // 设置当前模型的数据库连接
    protected $connection = [];

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->modelKey) || empty($this->modelKey) || cache('modelKey') != $this->modelKey) {
            exit(json_encode(['msg' => '非法操作！', 'code' => 711]));
        }
        $this->connection = config('cms.db');
    }


    /**
     * 列表
     * @param array $map
     * @param int $page
     * @param int $limit
     * @param string $order
     * @param bool|true $field
     * @return mixed
     */
    public function getList($map = [], $page = 1, $limit = 10, $order = "vod_year desc", $field = '')
    {
        $key = md5(json_encode($map) . $page . $limit . $order . $field . request()->baseFile() . request()->controller() . request()->action() . request()->module());
        $ret = cache($key);
        if ($ret) {
            return $ret;
        }
        if (isset($map['user'])) {
            $user = $map['user'];
            unset($map['user']);
            if (config('commoncfg.show_xx') == 1) {
                // 会员控制
                if (!$user || !isset($user['group_id']) || ($user['group_id'] < config('commoncfg.member_group_limit'))) {
                    $order = "vod_year asc";
                }
            }
        }
        if (isset($map['sql'])) {
            $map = $map['sql'];
        }
        $obj = $this->where($map)->field('vod_id')->orderRaw($order);
        $ret = [];
        $ret['page'] = (int)$page;
        $ret['limit'] = (int)$limit;
        if ($page) {
            $obj = $obj->page($page)->limit($limit);
        }
        $sql = $obj->fetchSql(true)->select();
        // 查出ids
        $ids = $this->query($sql);
        if (empty($ids)) {
            $ret['list'] = [];
            return $ret;
        }
        // 根据id查列表
        $field = $field ? $field : 'vod_id,type_id,type_id_1,vod_name,vod_score,vod_status,vod_class,vod_pic,vod_actor,vod_director,vod_blurb,vod_remarks,vod_area,vod_lang,vod_year';
        $ids = implode(',', array_column($ids, 'vod_id'));
        $ret['list'] = $this->where('vod_id', 'in', $ids)->field($field)->order($order)->select();
        cache($key, $ret, 600);
        return $ret;
    }

    /**
     * 结果重复，弃用
     *
     * @param [type] $where
     * @param [type] $order
     * @param string $alias
     * @param integer $limit
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getRandList($where, $order, $alias = 't1', $limit = 9)
    {
        $sql = "SELECT {$alias}.vod_id, {$alias}.vod_name, {$alias}.vod_pic, {$alias}.vod_play_url, {$alias}.vod_remarks, {$alias}.vod_score
FROM `mac_vod` AS {$alias} JOIN (SELECT ROUND(RAND() * ((SELECT MAX(vod_id) FROM `mac_vod`)-(SELECT MIN(vod_id) FROM `mac_vod`))+(SELECT MIN(vod_id) FROM `mac_vod`)) AS vod_id) AS t2
WHERE {$alias}.vod_id >= t2.vod_id AND {$where} 
ORDER BY {$order} LIMIT {$limit};";
        $ret['list'] = $this->query($sql);
        foreach ($ret['list'] as $key => $val) {
            $ret['list'][$key]['vod_pic'] = str_replace('mac://', 'http://', $val['vod_pic']);
        }
        return $ret;
    }

    public function getVodPicAttr($v)
    {
        $str = str_replace('mac://', 'http://', $v);
        if (strpos($str, 'http') === false) {
            return config('wechat.cms_host') . '/' . $str;
        }
        return $str;
    }

    public function getVideoFieldGroup($field = '')
    {
        $list = $this->field($field)->group($field)->select();
        if (count($list) <= 0) return [];
        return $list->toArray();
    }

    public function getVideoDetail($vid = '')
    {
        if ($info = cache(md5($vid))) {
            return $info;
        }
        $map = [];
        $map[] = is_numeric($vid) ? ['vod_id', 'eq', $vid] : ['vod_name', 'eq', $vid];
        $info = $this->where($map)->find();
        if (!$info) {
            return false;
        }
        cache(md5($vid), $info, 300);
        return $info;
    }

    public function searchKeywords($map = [])
    {
        $field = 'vod_id,vod_name,vod_status,vod_pic,vod_actor,vod_year,vod_class,vod_area,vod_lang';
        $info = $this->cache('search_list', 300)->field($field)->where($map)->limit(0, 20)->order('vod_year desc, vod_hits_week desc')->select();
        if (!$info) {
            return [];
        }
        return $info;
    }

    public function searchTabs($map = [], $order = 'vod_year desc, vod_hits_week desc')
    {
        $field = 'vod_id,vod_name';
        $info = $this->cache('search_tab_list', 300)->field($field)->where($map)->limit(0, 30)->order($order)->select();
        if (!$info) {
            return [];
        }
        return $info;
    }
    /**
     * 随机取页数
     *
     * @param [Array] $map
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getRandByPage($map = [], $limit = 9, $order = '')
    {
        // 获取总条数
        $count = cache(md5(json_encode($map)));
        if (!$count) {
            $count = $this->where($map)->count('vod_id');
            cache(md5(json_encode($map)), $count, 86400);
        }
        if (!$count) return [];
        // 取得总页数
        $count_page = round($count / $limit) - 1;
        // 随机一页
        $page = mt_rand(1, $count_page);
        return $this->getList($map, $page, $limit, $order);
    }
}
